package cn.wolfcode.crm.exception;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import com.sun.webkit.network.data.Handler;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class CRMExceptionHandler {

    /**
     * 捕获运行过程中的运行时异常
     *
     * @param ex
     * @param model
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @ExceptionHandler(RuntimeException.class)
    public String handleException(Exception ex, Model model, HandlerMethod handlerMethod, HttpServletResponse response) throws ServletException, IOException {
        ex.printStackTrace();
        //判断当前的方法是否是ajax方法 如果是会有@ResponseBody注解
        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
            JsonResult jsonResult = new JsonResult("操作失败,请联系管理员", false);
            //通过response对象输出数据(json字符串)
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(jsonResult));
            return null;
        }
        //如果是 返回json 字符串
        //如果不是 返回错误视图
        model.addAttribute("ex", ex);
        return "common/error";
    }

    /**
     * 捕获运行过程中的 UnauthorizedException 没有权限
     *
     * @param ex
     * @param model
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @ExceptionHandler(UnauthorizedException.class)
    public String handleUnauthorizedException(Exception ex, Model model, HandlerMethod handlerMethod,
                                              HttpServletResponse response) throws ServletException, IOException {
        ex.printStackTrace();
        //判断当前的方法是否是ajax方法 如果是会有@ResponseBody注解
        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
            JsonResult jsonResult = new JsonResult("您没有该权限,请联系管理员", false);
            //通过response对象输出数据(json字符串)
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(jsonResult));
            return null;
        }
        //如果是 返回json 字符串
        //如果不是 返回错误视图
        model.addAttribute("ex", ex);
        return "common/nopermission";
    }
}
